<template>
  <div class="commonTableSty rightDrawerWithoutCol">
    <a-table :columns="columns" :rowKey="(record, index) => index" :dataSource="brandData" :pagination="false">
      <template slot="brandName" slot-scope="text, record">
        <a-input
          v-if="record.editable"
          :class="{hasError:record.nameError}"
          v-model="record.name"
          :maxLength="50"
          @change="handlerChange(record,'name',$event)"></a-input>
        <table-ellipsis v-else :text="record.name"></table-ellipsis>
      </template>
      <template slot="remark" slot-scope="text, record">
        <a-input v-if="record.editable" v-model="record.remark" :maxLength="200" />
        <table-ellipsis v-else :text="record.remark||'-'"></table-ellipsis>
      </template>
      <template slot="operation" slot-scope="text, record,index">
        <!-- 没有id或者是编辑状态展示“保存/取消” -->
        <template v-if="!record.id||record.editable">
          <a @click="saveEdit(record,index)">{{ $t('save') }}</a>
          <a-divider type="vertical" />
          <a @click="handleCancle(record,index)">{{ $t('cancel') }}</a>
        </template>
        <!-- 编辑/删除 -->
        <template v-else>
          <a @click="handelEdit(index)">{{ $t('edit') }}</a>
          <a-divider type="vertical" />
          <a @click="deleteListBrand(record)">{{ $t('delete') }}</a>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import HasNoPermissionTip from '@/components/HasNoPermissionTip'
// 需要检测的字段标志符
const checkFieldConfig = {
  nameError: false
}
const oneRecord = {
  id: '',
  name: '',
  remark: '',
  editable: true,
  error: false,
  index: -1,
  ...checkFieldConfig
}
export default {
  name: 'NewBrand',
  components: {
    TableEllipsis,
    HasNoPermissionTip
  },
  computed: {
    ...mapState({
      brandData: (state) => state.brand.brandData
    }),
    columns () {
      // 表头
      const columns = [
        {
          title: this.$t('brandName'),
          scopedSlots: { customRender: 'brandName' }
        },
        {
          title: this.$t('remark'),
          scopedSlots: { customRender: 'remark' }
        },
        {
          title: this.$t('operation'),
          width: 120,
          scopedSlots: { customRender: 'operation' }
        }
      ]
      return columns
    }
  },
  created () {

  },
  data () {
    return {
      backBrandList: [],
      rules: {
        name: {
          required: true,
          msg: ''
        }
      }
    }
  },
  mounted () {
    this.backBrandList = []
    this.$store.dispatch('getBrandData').then(() => {
      // 备份表格数据 用于取消
      this.backBrandList = this.$commonFun.deepCopy(this.brandData)
    })
  },
  methods: {
    addList () {
      const objItem = {
        ...oneRecord,
        index: Math.random()
      }
      this.brandData.unshift(objItem)
      this.backBrandList.unshift(objItem)
    },
    saveEdit (record, index) {
      const vm = this
      let saveBrand = {}
      if (!this.checkData(record)) {
        return
      }
      const values = {
        name: record.name,
        remark: record.remark
      }
      if (record.id) {
        values.id = record.id
        saveBrand = vm.$api.editBrand(values)
      } else {
        saveBrand = vm.$api.addBrand(values)
      }
      saveBrand
        .then((res) => {
          vm.$message.success(vm.$t('success'))
          // eslint-disable-next-line no-param-reassign
          record.editable = false
          if (!record.id) {
            vm.$set(record, 'id', res.data)
          }
          vm.backBrandList[index] = { ...record } // 保存成功后同步备份
        })
        .catch(() => {
          // eslint-disable-next-line no-param-reassign
          record.editable = true
          vm.$set(vm.backBrandList[index], 'editable', true)
        })
    },
    handleCancle (record, index) {
      const vm = this
      this.$confirm({
        title: vm.$t('cancelSave'),
        content: vm.$t('cancelSaveTip'),
        onOk () {
          // eslint-disable-next-line no-param-reassign
          record.editable = false
          vm.$set(vm.backBrandList[index], 'editable', false)
          if (record.id) {
            vm.$set(vm.brandData, index, vm.$commonFun.deepCopy(vm.backBrandList[index]))
          } else {
            vm.brandData.splice(index, 1)
            vm.backBrandList.splice(index, 1)
          }
        },
        onCancel () { }
      })
    },
    handelEdit (index) {
      const vm = this
      vm.$set(vm.brandData[index], 'editable', true)
      vm.$set(vm.backBrandList[index], 'editable', true)
    },
    deleteListBrand (record) {
      const vm = this
      this.$confirm({
        title: vm.$t('deleteBrand'),
        content: vm.$t('deleteBrandTip'),
        class: 'confirmStyle',
        icon: '<Icon >',
        width: 378,
        onOk () {
          vm.$api.batchDeleteBrand({ ids: [record.id] }).then(() => {
            vm.brandData.splice(vm.brandData.findIndex(item => item.id === record.id), 1)
            vm.backBrandList.splice(vm.backBrandList.findIndex(item => item.id === record.id), 1)
            vm.$message.success(vm.$t('successfullyDelete'))
            // 否则新增中的更新文件被刷掉
          })
        },
        onCancel () { }
      })
    },
    handlerChange (record, key, ev) {
      if (this.checkIsEmpty(ev.target.value)) {
        // eslint-disable-next-line no-param-reassign
        record[key + 'Error'] = true
      } else {
        // eslint-disable-next-line no-param-reassign
        record[key + 'Error'] = false
        // eslint-disable-next-line no-param-reassign
        record[key] = ev.target.value.replace(/^\s+|\s+$/g, '')
      }
    },
    checkIsEmpty (value) {
      const val = value ? value.replace(/^\s+|\s+$/g, '') : ''
      return val.length === 0
    },
    checkData (data) {
      let checkOk = true
      // eslint-disable-next-line no-restricted-syntax
      for (const key in data) {
        if (this.rules[key] && this.rules[key].required) {
          if (this.checkIsEmpty(data[key])) {
            // eslint-disable-next-line no-param-reassign
            data[key + 'Error'] = true
            checkOk = false
          } else {
            // eslint-disable-next-line no-param-reassign
            data[key + 'Error'] = false
          }
        }
      }
      if (!checkOk) {
        this.$message.error(this.$t('completeInformation'))
      }
      return checkOk
    }
  }
}
</script>
